﻿using DevExpress.Utils;
using DevExpress.XtraEditors;
using DevExpress.XtraEditors.Controls;
using DevExpress.XtraGrid.Views.Grid;
using RecruitStudents.Client.BLL;
using RecruitStudents.Utility;
using RecruitStudents.Utility.Const;
using RecruitStudents.Utility.Helper;
using RecruitStudents.Utility.Model;
using RecruitStudents.Utility.Push;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace RecruitStudents.Client.Score
{
    public partial class Score_ScorePublishForm_List : BaseForm
    {
        private DataTable dtExport;
        public string PublicMark = ""; //打印名单的备注
        ServiceScore serviceScore = new ServiceScore();
        ServiceComm serviceComm = new ServiceComm();
        public Score_ScorePublishForm_List()
        {
            InitializeComponent();
            this.cmbExamRoom.Properties.DataSource = null;
            this.cmbTeacher.Properties.DataSource = null;
            this.cmbTeacher.Properties.Columns.Clear();
            this.cmbTeacher.Properties.NullText = "";
            BindExamRoom();
            BindSpec();
        }
        private void BindSpec()
        {
            using (DataTable dt = serviceComm.GetSpecialityKindsTable(SessionerHelper.SystemYear))
            {
                this.cmbZY.Properties.NullText = "";
                this.cmbZY.Properties.Columns.Add(new LookUpColumnInfo("SpecialityKindsNO", "专业代码"));
                this.cmbZY.Properties.Columns.Add(new LookUpColumnInfo("SpecialityKindsName", "专业名称"));
                this.cmbZY.Properties.DataSource = dt;
                this.cmbZY.Properties.DisplayMember = "SpecialityKindsName";
                this.cmbZY.Properties.ValueMember = "SpecialityKindsNO";
                this.cmbZY.Properties.Columns[0].Visible = false;
                if (dt != null && dt.Rows.Count > 0)
                {
                    this.cmbZY.EditValue = SessionerHelper.SpecialityKindsNO.ToSafeString();
                }
            }
        }
        private void BindExamRoom()
        {
            string strExaminationID = SessionerHelper.ExaminationID;
            using (DataTable dt = serviceComm.GetExamRoomTableByEntretenimientohID(strExaminationID))
            {
                if (dt != null && dt.Rows.Count > 0)
                {
                    DataRow drNew = dt.NewRow();
                    drNew["ExamRoomNO"] = "";
                    drNew["ExamRoomName"] = "全部";
                    dt.Rows.InsertAt(drNew, 0);
                }
                this.cmbExamRoom.Properties.NullText = "";
                this.cmbExamRoom.Properties.Columns.Add(new LookUpColumnInfo("ExamRoomNO", "考场代码"));
                this.cmbExamRoom.Properties.Columns.Add(new LookUpColumnInfo("ExamRoomName", "考场名称"));
                this.cmbExamRoom.Properties.DataSource = dt;
                this.cmbExamRoom.Properties.DisplayMember = "ExamRoomName";
                this.cmbExamRoom.Properties.ValueMember = "ExamRoomNO";
                this.cmbExamRoom.Properties.Columns[0].Visible = false;
            }
        }
        private void BindTeacher()
        {
            this.cmbTeacher.Properties.Columns.Clear();
            this.cmbTeacher.Properties.DataSource = null;
            this.cmbTeacher.Properties.NullText = "";
            this.cmbTeacher.EditValue = "";
            if (cmbExamRoom.EditValue == null || cmbExamRoom.EditValue.ToSafeString().Length == 0)
            {
                return;
            }
            this.cmbTeacher.Properties.Columns.Add(new LookUpColumnInfo("LoginName", "考官登录名"));
            this.cmbTeacher.Properties.Columns.Add(new LookUpColumnInfo("ExaminerName", "考官姓名"));
            DataTable dt = serviceComm.GetTeacherList(cmbExamRoom.EditValue.ToSafeString());
            if (dt != null && dt.Rows.Count > 0)
            {
                DataRow drNew = dt.NewRow();
                drNew["LoginName"] = "";
                drNew["ExaminerName"] = "全部";
                dt.Rows.InsertAt(drNew, 0);
            }
            this.cmbTeacher.Properties.DataSource = dt;
            this.cmbTeacher.Properties.DisplayMember = "ExaminerName";
            this.cmbTeacher.Properties.ValueMember = "LoginName";
            this.cmbTeacher.Properties.Columns[0].Visible = false;
        }
        private void cmbExamRoom_EditValueChanged(object sender, EventArgs e)
        {
            if (cmbExamRoom.EditValue == null || cmbExamRoom.EditValue.ToSafeString().Length == 0)
            {
                return;
            }
            else
            {
                BindTeacher();
                BindDataGrid();
            }
        }
        private void btnQuery_Click(object sender, EventArgs e)
        {
            this.BindDataGrid();
        }
        private void BindDataGrid()
        {
            this.dgvQD.DataSource = null;
            string strExamRoomID = string.Empty;
            if (cmbExamRoom.EditValue != null && !string.IsNullOrEmpty(cmbExamRoom.EditValue.ToString()))
            {
                strExamRoomID = cmbExamRoom.EditValue.ToString().Trim();
            }
            string strTeacher = string.Empty;
            if (this.cmbTeacher.EditValue != null)
            {
                strTeacher = this.cmbTeacher.EditValue.ToString();
            }
            string strSpec = string.Empty;
            if (this.cmbZY.EditValue != null)
            {
                strSpec = this.cmbZY.EditValue.ToString();
            }
            string strSFYSB = "1";
            using (DataTable dt = serviceScore.GetScoreQueryUp(strSFYSB,strExamRoomID, strTeacher, SessionerHelper.ExaminationID, SessionerHelper.ExamPlaceID, strSpec, SessionerHelper.ExamLevel))
            {
                if (dt != null && dt.Rows.Count > 0)
                {
                    this.dgvQD.DataSource = dt;
                    for (int i = 0; i < gridView1.Rows.Count; i++)
                    {
                        if (gridView1.Rows[i].DataRow["IsPass"].ToSafeString() == "1")
                        {
                            gridView1.SelectRow(i);
                        }
                        else
                        {
                            gridView1.UnselectRow(i);
                        }
                    }
                    dtExport = dt.Copy();
                }
                else
                {
                    dtExport = null;
                }
            }
        }
        private void cmbTeacher_EditValueChanged(object sender, EventArgs e)
        {
            if (cmbExamRoom.EditValue != null || !string.IsNullOrEmpty(cmbExamRoom.EditValue.ToString()))
            {
                this.BindDataGrid();
            }
        }
        #region 定义属性
        private EMFStreamPrintDocument printDoc = null;
        private System.Windows.Forms.PrintDialog PrintDialog1 = new PrintDialog();
        private string m_ReportName = string.Empty;
        private string ReportName
        {
            get
            {
                return this.m_ReportName;
            }
            set
            {
                this.m_ReportName = value;
            }
        }
        private string m_ReportPath = string.Empty;
        private string ReportPath
        {
            get
            {
                return this.m_ReportPath;
            }
            set
            {
                this.m_ReportPath = value;
            }
        }
        private DataTable m_ReportDataSources = null;
        private DataTable ReportDataSources
        {
            get
            {
                return this.m_ReportDataSources;
            }
            set
            {
                this.m_ReportDataSources = value;
            }
        }
        #region 获取报表的数据源
        /// <summary>
        /// 获取报表的数据源
        /// </summary>
        /// <param name="IsCheck"></param>
        private void GetReportDataSources_list(bool IsCheck)
        {
            DataTable dtReport = new DataTable();

            dtReport.Columns.Add("TitleRow");
            dtReport.Columns.Add("TitleColumn");
            dtReport.Columns.Add("AllowExamID");
            dtReport.Columns.Add("Name");
            dtReport.Columns.Add("Sex");
            DataRow drReport;

            int TitleRow = 1;
            int TitleColumn = 1;

            bool flag = false;

            if (IsCheck)
            {
                for (int i = 0; i < gridView1.RowCount; i++)
                {
                    drReport = dtReport.NewRow();
                    drReport[0] = TitleRow;
                    drReport[1] = TitleColumn;
                    drReport[2] = gridView1.Rows[i].DataRow["AllowExamID"].ToSafeString();
                    drReport[3] = gridView1.Rows[i].DataRow["StudentName"].ToSafeString();
                    drReport[4] = gridView1.Rows[i].DataRow["SexName"].ToSafeString();
                    dtReport.Rows.Add(drReport);

                    TitleColumn++;

                    if (TitleColumn == 3)
                    {
                        TitleColumn = 1;
                        TitleRow++;
                    }
                }
            }
            else
            {
                for (int i = 0; i < 20; i++)
                {
                    drReport = dtReport.NewRow();
                    drReport[0] = "";
                    drReport[1] = "";
                    drReport[2] = "";
                    drReport[3] = "";
                    dtReport.Rows.Add(drReport);
                }
            }


            ReportDataSources = dtReport.Copy();

            dtReport = null;

        }
        #endregion
        #endregion
        private void btnExport_Click(object sender, EventArgs e)
        {
            this.BindDataGrid();
            if (dtExport != null && dtExport.Rows.Count > 0)
            {
                GetReportDataSources_list(true);

                string strExamYear = "";
                string strExamAddress = "";
                string strExamDate = "";
                string strExamType = "";
                string strExamRoom = "";

                string strRemark = "";

                strExamYear = DateTime.Now.Year.ToString().Trim() + "招生-----考点：";
                strExamAddress = SessionerHelper.ExamPlaceName;
                strExamDate = "发布日期：" + DateTime.Now.ToString("yyyy-MM-dd").Trim();
                strExamRoom = "";

                if (PublicMark.Trim() != "")
                {
                    strRemark = "备注： " + PublicMark.Trim();
                }

                if (SessionerHelper.ExamLevel == "1")
                {
                    strExamType = SessionerHelper.SpecialityKinds + "初试人员合格名单";
                }
                else if (SessionerHelper.ExamLevel == "2")
                {
                    strExamType = SessionerHelper.SpecialityKinds + "复试人员合格名单";
                }
                else if (SessionerHelper.ExamLevel == "3")
                {
                    strExamType = SessionerHelper.SpecialityKinds + "三试人员合格名单";
                }

                ReportPath = "PassStudentsPrint.rdlc";
                ReportName = "Act";



                this.rpviewPrint.Reset();
                this.rpviewPrint.LocalReport.ReportPath = ReportPath;
                this.rpviewPrint.LocalReport.DataSources.Clear();

                this.rpviewPrint.LocalReport.DataSources.Add(new Microsoft.Reporting.WinForms.ReportDataSource("dsReport_dtPass", ReportDataSources));


                Microsoft.Reporting.WinForms.ReportParameter ExamYear = new Microsoft.Reporting.WinForms.ReportParameter("ExamYear", strExamYear);
                Microsoft.Reporting.WinForms.ReportParameter ExamAddress = new Microsoft.Reporting.WinForms.ReportParameter("ExamAddress", strExamAddress);
                Microsoft.Reporting.WinForms.ReportParameter ExamDate = new Microsoft.Reporting.WinForms.ReportParameter("ExamDate", strExamDate);
                Microsoft.Reporting.WinForms.ReportParameter ExamType = new Microsoft.Reporting.WinForms.ReportParameter("ExamType", strExamType);
                Microsoft.Reporting.WinForms.ReportParameter ExamRoom = new Microsoft.Reporting.WinForms.ReportParameter("ExamRoom", strExamRoom);
                Microsoft.Reporting.WinForms.ReportParameter ReMark = new Microsoft.Reporting.WinForms.ReportParameter("ReMark", strRemark);

                this.rpviewPrint.LocalReport.SetParameters(new Microsoft.Reporting.WinForms.ReportParameter[] { ExamYear });
                this.rpviewPrint.LocalReport.SetParameters(new Microsoft.Reporting.WinForms.ReportParameter[] { ExamAddress });
                this.rpviewPrint.LocalReport.SetParameters(new Microsoft.Reporting.WinForms.ReportParameter[] { ExamDate });
                this.rpviewPrint.LocalReport.SetParameters(new Microsoft.Reporting.WinForms.ReportParameter[] { ExamType });
                this.rpviewPrint.LocalReport.SetParameters(new Microsoft.Reporting.WinForms.ReportParameter[] { ExamRoom });
                this.rpviewPrint.LocalReport.SetParameters(new Microsoft.Reporting.WinForms.ReportParameter[] { ReMark });

                this.rpviewPrint.LocalReport.Refresh();
                this.rpviewPrint.RefreshReport();

                if (this.printDoc == null)
                {
                    this.printDoc = new EMFStreamPrintDocument(this.rpviewPrint.LocalReport, this.ReportName);
                }

                SaveFileDialog kk = new SaveFileDialog();
                kk.Title = "保存WORD文件";
                kk.Filter = "WORD文件(*.doc) |*.doc |所有文件(*.*) |*.*";
                kk.FilterIndex = 1;
                kk.FileName = "成绩公布" + DateTime.Now.ToString("yyyyMMdd");
                kk.ShowDialog();
                if (kk.FileName.IndexOf(":") < 0) return; //被点了取消 

                string saveFileName = kk.FileName;

                Microsoft.Reporting.WinForms.Warning[] warnings;
                string[] streamids;
                string mimeType;
                string encoding;
                string extension;

                byte[] bytes = rpviewPrint.LocalReport.Render("Word", null, out mimeType, out encoding, out extension, out streamids, out warnings);

                FileStream fs = new FileStream(saveFileName, FileMode.Create);
                fs.Write(bytes, 0, bytes.Length);
                fs.Close();
            }
            else
            {
                DevHelper.ShowErrorMessageBox("暂时还没有考生成绩,无法进行导出打印!");
            }
        }
        private void btnScoreUp_Click(object sender, EventArgs e)
        {
            try
            {
                string strSpec = string.Empty;
                if (this.cmbZY.EditValue != null)
                {
                    strSpec = this.cmbZY.EditValue.ToString();
                }
                else
                {
                    strSpec = SessionerHelper.SpecialityKindsNO;
                }
                DataTable dtPublishTable = serviceScore.GetExamResultsPublishTable(SessionerHelper.ExamPlaceID, strSpec, SessionerHelper.ExamLevel);
                if (dtPublishTable != null && dtPublishTable.Rows.Count > 0)
                {
                    if (dtPublishTable.Rows[0]["IsIn"].ToSafeString() == "")
                    {
                        DevHelper.ShowErrorMessageBox("外网成绩已经发布!");
                        return;
                    }
                    if (dtPublishTable.Rows[0]["IsOut"].ToSafeString() == "1")
                    {
                        DevHelper.ShowErrorMessageBox("外网成绩已经发布!");
                        return;
                    }
                }
                if (XtraMessageBox.Show("请确认是否内网成绩发布?", "成绩发布", MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.OK)
                {
                    string strAllowExamID = string.Empty;
                    string strIsPass = string.Empty;
                    if (GetSelectRowsValue(out strAllowExamID, out strIsPass))
                    {
                        Score_ScorePublishForm_Option option = new Score_ScorePublishForm_Option();
                        if (option.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                        {
                            string strRemark = option.strRemark;
                            string strExamLevel = SessionerHelper.ExamLevel;
                            string strExamPlaceID = SessionerHelper.ExamPlaceID;
                            string strSpecialityKindsNO = strSpec;
                            string strIsIn = "1";
                            string strMessage = serviceScore.SavePublishData(strAllowExamID, strIsPass, strExamLevel, strExamPlaceID, strSpecialityKindsNO, strRemark, strIsIn);
                            if (strMessage.Length == 0)
                            {
                                DevHelper.ShowInfoMessageBox("内网成绩发布成功!");
                                BindDataGrid();
                            }
                            else
                            {
                                DevHelper.ShowErrorMessageBox("内网成绩发布成绩出现错误:" + strMessage);
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                DevHelper.ShowErrorMessageBox("内网成绩发布成绩出现错误:" + ex.Message);
            }
        }
        private void gridView1_DoubleClick(object sender, EventArgs e)
        {
            if (gridView1.GetFocusedValue() != null)
            {
                GridView rows = sender as GridView;
                int[] inteurm = rows.GetSelectedRows();
                if (inteurm != null && inteurm.Length > 0)
                {
                    Score_ScoreUpForm_Option option = new Score_ScoreUpForm_Option();
                    option.strAllowExamID = rows.Rows[inteurm[0]].DataRow["AllowExamID"].ToString();
                    option.strSpecialityKindsNO = rows.Rows[inteurm[0]].DataRow["SpecialityKindsNO"].ToString();
                    option.strExamLevel = rows.Rows[inteurm[0]].DataRow["ExamLevel"].ToString();
                    option.ShowForm();
                }
            }
        }
        private bool GetSelectRowsValue(out string strAllowExamID, out string strIsPass)
        {
            strAllowExamID = string.Empty;
            strIsPass = string.Empty;
            GridRowCollection gridRows = gridView1.SelectedRows;
            if (gridRows != null && gridRows.Count > 0)
            {
                for (int i = 0; i < gridView1.Rows.Count; i++)
                {
                    string strAllowExamID_New = gridView1.Rows[i].DataRow["AllowExamID"].ToString();
                    bool result = false;
                    foreach (GridRow dr in gridRows)
                    {
                        if (strAllowExamID_New == dr.DataRow["AllowExamID"].ToSafeString())
                        {
                            result = true;
                            break;
                        }
                    }
                    if (result)
                    {
                        if (strAllowExamID.Length == 0)
                        {
                            strAllowExamID = gridView1.Rows[i].DataRow["AllowExamID"].ToString();
                            strIsPass = "1";
                        }
                        else
                        {
                            strAllowExamID += "," + gridView1.Rows[i].DataRow["AllowExamID"].ToString();
                            strIsPass += ",1";
                        }

                    }
                    else
                    {
                        if (strAllowExamID.Length == 0)
                        {
                            strAllowExamID = gridView1.Rows[i].DataRow["AllowExamID"].ToString();
                            strIsPass = "0";
                        }
                        else
                        {
                            strAllowExamID += "," + gridView1.Rows[i].DataRow["AllowExamID"].ToString();
                            strIsPass += ",0";
                        }
                    }
                }
                return true;
            }
            else
            {
                DevHelper.ShowInfoMessageBox("您还没有选择考生数据,无法进行上报!");
                return false;
            }
        }
        private void btnScoreUp_WW_Click(object sender, EventArgs e)
        {
            try
            {
                string strSpec = string.Empty;
                if (this.cmbZY.EditValue != null)
                {
                    strSpec = this.cmbZY.EditValue.ToString();
                }
                else
                {
                    strSpec = SessionerHelper.SpecialityKindsNO;
                }
                DataTable dtPublishTable = serviceScore.GetExamResultsPublishTable(SessionerHelper.ExamPlaceID, strSpec, SessionerHelper.ExamLevel);
                if (dtPublishTable == null)
                {
                    DevHelper.ShowErrorMessageBox("请先内网发布成绩再进行外网发布!");
                    return;
                }
                if (dtPublishTable != null && dtPublishTable.Rows.Count > 0)
                {
                    if (dtPublishTable.Rows[0]["IsIn"].ToSafeString() == "")
                    {
                        DevHelper.ShowErrorMessageBox("请先内网发布成绩再进行外网发布!");
                        return;
                    }
                    else if (dtPublishTable.Rows[0]["IsOut"].ToSafeString() == "1")
                    {
                        DevHelper.ShowErrorMessageBox("外网成绩已经发布!");
                        return;
                    }
                }

                if (XtraMessageBox.Show("请确认是否进行外网成绩发布?", "外网发布确认", MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.OK)
                {
                    string strAllowExamID = string.Empty;
                    string strIsPass = string.Empty;
                    if (GetSelectRowsValue(out strAllowExamID, out strIsPass))
                    {
                        Score_ScorePublishForm_Option option = new Score_ScorePublishForm_Option();
                        if (option.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                        {
                            string strRemark = option.strRemark;

                            PublicMark = strRemark;

                            string strExamLevel = SessionerHelper.ExamLevel;
                            string strExamPlaceID = SessionerHelper.ExamPlaceID;
                            string strSpecialityKindsNO = strSpec;
                            string strIsIn = "2";
                            string strMessage = serviceScore.SavePublishData(strAllowExamID, strSpecialityKindsNO, strExamLevel, strExamPlaceID,
                             strIsPass, strRemark, strIsIn);
                            if (strMessage.Length == 0)
                            {
                                Thread thread = new Thread(new ThreadStart(Method));
                                thread.Start();
                                DevHelper.ShowInfoMessageBox("外网成绩发布成功!");
                            }
                            else
                            {
                                DevHelper.ShowErrorMessageBox("外网成绩发布出现错误:" + strMessage);
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                DevHelper.ShowErrorMessageBox("外网成绩发布出现错误:" + ex.Message);
            }
        }
        private void Method()
        {
            if (gridView1.DataSource != null && gridView1.Rows != null && gridView1.Rows.Count > 0)
            {
                string strZYMC = string.Empty;
                try
                {
                    strZYMC = cmbZY.Text;
                }
                catch
                { }
                List<TB_Notice> listNotice = new List<TB_Notice>();
                string strMessage = SessionerHelper.ExamPlaceName + strZYMC + ConstExamLevel.GetExamLevel(SessionerHelper.ExamLevel.ToSafeInt()) + "成绩已发布,请至网站或App查询";
                strMessage += "。" + PublicMark;
                for (int i = 0; i < gridView1.Rows.Count; i++)
                {
                    TB_Notice notice = new TB_Notice();
                    notice.SignUpID = gridView1.Rows[i].DataRow["SignUpID"].ToSafeString();
                    notice.NoticeType = "private";
                    notice.NoticeTitle = "通知:成绩已更新,请查看";
                    notice.Message = strMessage;
                    notice.IsRead = "0";
                    notice.CreateTime = DateTime.Now;
                    notice.IsActive = "1";
                    listNotice.Add(notice);
                }
                if (new ServiceConsult().SaveNoticeList(listNotice))
                {
                    foreach (TB_Notice notice in listNotice)
                    {
                        #region 推送消息
                        PushHelper objJPush = new PushHelper();
                        TB_ConsultTitle objTitle = new TB_ConsultTitle();
                        TB_ConsultReply objReply = new TB_ConsultReply();
                        objTitle.UsersID = notice.SignUpID;
                        objTitle.ID = notice.NoticeID;
                        objTitle.ConsultTitle = notice.NoticeTitle;
                        objTitle.TypeID = ConsultType.TZ;
                        objJPush.Push(objTitle, objReply);
                        #endregion
                    }
                }
            }
        }
        protected override void OnLoad(EventArgs e)
        {
            gridView1.IndicatorWidth = 40;
            gridView1.PreviewIndent = 0;
            gridView1.CustomDrawRowIndicator += gridView1_CustomDrawRowIndicator;
            gridView1.CustomDrawCell += gridView1_CustomDrawCell;
            base.OnLoad(e);
        }
        void gridView1_CustomDrawRowIndicator(object sender, RowIndicatorCustomDrawEventArgs e)
        {
            e.Appearance.TextOptions.HAlignment = HorzAlignment.Far;
            if (e.Info.IsRowIndicator && e.RowHandle >= 0)
            {
                e.Info.DisplayText = (e.RowHandle + 1).ToString();
            }
        }
        private void gridView1_CustomDrawCell(object sender, DevExpress.XtraGrid.Views.Base.RowCellCustomDrawEventArgs e)
        {
            if (gridView1.GetRow(e.RowHandle) == null)
            {
                return;
            }
            else
            {
                //获取所在行指定列的值
                string state = gridView1.GetRowCellValue(e.RowHandle, "IsPass").ToString();
                //比较指定列的状态
                if (state == "1")
                {
                    e.Appearance.BackColor = Color.Red;//设置此行的背景颜色
                }
            }
        }
    }
}
